package Views.Destino;

import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import Fisica.Destino.DAODestino;
import Inteface.InterfaceGrilla;
import Inteface.InterfacePanel;
import Modelo.Destino;

import javax.swing.JTextField;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class DestinoGrilla extends JPanel implements InterfaceGrilla, InterfacePanel{
	private JTable table;

	public DefaultTableModel model;
	private TableRowSorter<TableModel> modeloOrdenado;
	/**Atributos de alinear tablas*/
	public DefaultTableCellRenderer alinearCentro;
	private JTextField tfFiltro;
	/**
	 * Create the panel.
	 */
	public DestinoGrilla(int id) {
		setLayout(null);
		this.setVisible(true);
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 11, 580, 383);
		add(scrollPane);
		
		table = new JTable();
		scrollPane.setViewportView(table);
		
		tfFiltro = new JTextField();
		tfFiltro.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
			}
		});
		tfFiltro.setBounds(10, 398, 116, 20);
		add(tfFiltro);
		tfFiltro.setColumns(10);

		this.alinear();
		this.init(id);
		
		this.autoFiltro();

	}
	
	public void init(int id){
	   model = new DefaultTableModel(
			new Object[][] {
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
			},
			new String[] {
				"ID", "Sucursal", "Seccion", "Oficina"
			}
		) {
			Class[] columnTypes = new Class[] {
				String.class, String.class, String.class, String.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
		};		
		table.setModel(model);
		
		table.getColumnModel().getColumn(0).setPreferredWidth(50);
		
		List<Object>list = null;
		
		DAODestino dt = new DAODestino();
		list = dt.list();
		
		if(list.size()>0 ){
			model.setRowCount(0);
			Destino t;
			for (Object x : list) {
				t = (Destino) x;				
//				"ID", "Marca", "Modelo", "Codigo"
				model.addRow(new Object[] {
						t.getId(),
						t.getSucursal(),
						t.getSeccion(),
						t.getOficina()
						
						});
			}
		}
		
		//DENTRO DEL METODO DONDE SE CARGA LA TABLA
				table.getColumnModel().getColumn(0).setCellRenderer(alinearCentro);
				table.getColumnModel().getColumn(1).setCellRenderer(alinearCentro);
		        table.getColumnModel().getColumn(2).setCellRenderer(alinearCentro);
		        table.getColumnModel().getColumn(3).setCellRenderer(alinearCentro);
		        
		     	
		        
		if(list.size()>0 && id >= 0){
			table.setSelectionMode(id);
		}
		
		
//		if(id >= 0)
//			table.setSelectionMode(id);
	}
	
	

	public int getRowSelected() {
		try {
			return table.getSelectedRow();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

	public void guardar() {
//		DAODestino th = new DAODestino();
//		int id = getRowSelected();
//		Destino t = (Destino) th.getById(Integer.valueOf(id));		
//		
////		"ID", "Marca", "Modelo", "Codigo"
//
//		int col = model.getColumnCount();
//		int row = model.getRowCount() -1;
//		boolean tiene = false;
//		for (int x = 1; x< col; x++) {
//			Object campo = model.getValueAt(row, x);
//			if((campo != null))
//				tiene = true;
//		}
//		if(tiene){
////			model.addRow(new Object[] {i, null, null, null});
//			
//			t.setModelo((String)table.getValueAt(id, 2));
//			t.setMarca((String)table.getValueAt(id, 1));
//			t.setCodigo((String)table.getValueAt(id, 3));
//			
//			th.insert(t);
//		}	
	}

	public void cancelar() {
		this.init(-1);		
	}

	public Object primero() {
		DAODestino dt = new DAODestino();
		return (Destino) dt.getFirst();		
	}

	public Object ultimo() {
		DAODestino dt = new DAODestino();
		return (Destino) dt.getLast();
	}

	public Object anterior() {
		DAODestino dt = new DAODestino();
		int row = table.getSelectedRow();
		int id = Integer.parseInt((String) table.getValueAt(row +1, 0));
		return (Destino) dt.getPre(id);
	}

	public Object posterior() {
		DAODestino dt = new DAODestino();
		int row = table.getSelectedRow();
		int id = Integer.parseInt((String) table.getValueAt(row +1, 0));
		return (Destino) dt.getPost(id);
	}
	
	@Override
	public int setprimero() {
		table.setRowSelectionInterval( 0, 0 );
		return Integer.parseInt((String)table.getValueAt(0, 0));
	}

	@Override
	public int setultimo() {
		int rows = model.getRowCount();
		table.setRowSelectionInterval( rows-1, rows-1 );
		return Integer.parseInt((String)table.getValueAt(rows-1, 0));
	}

	@Override
	public int setanterior() {
		int row = table.getSelectedRow();
		if(row > 0)
			table.setRowSelectionInterval( row-1, row-1 );
		else return setprimero();
		return Integer.parseInt((String)table.getValueAt(row-1, 0));
	}

	@Override
	public int setposterior() {
		int row = table.getSelectedRow();
		if(row >= (table.getRowCount()-1))
			return setultimo();
		else
			table.setRowSelectionInterval( row+1, row+1 );
		return Integer.parseInt((String)table.getValueAt(row+1, 0));
	}

	public boolean grilla() {
		return true;		
	}

	public boolean campos() {
		return false;		
	}

	@Override
	public int getPanel() {
		return 1;
	}

	@Override
	public void nuevo() {
		DAODestino dt = new DAODestino();
		int i = ((Destino) dt.getLast()).getId() +1;
		int col = model.getColumnCount();
		int row = model.getRowCount() -1;
		boolean tiene = false;
		for (int x = 1; x< col; x++) {
			Object campo = model.getValueAt(row, x);
			if((campo != null))
				tiene = true;
		}
		if(tiene)
			model.addRow(new Object[] {i, null, null, null});
	}
	
	/*Inicializo y cargo alineacinn de conlumnas en tablas*/
	public void alinear(){
		alinearCentro = new DefaultTableCellRenderer();					
		alinearCentro.setHorizontalAlignment(SwingConstants.CENTER);			
	}
	
	private void autoFiltro(){
        tfFiltro.addKeyListener(new KeyListener() {			
			@Override
			public void keyTyped(KeyEvent arg0) {
				}
			
			@Override
			public void keyReleased(KeyEvent arg0) {
				filtrar(null);
			}
			
			@Override
			public void keyPressed(KeyEvent arg0) {
				}
		});
        }
	
	 private void filtrar(ActionEvent e) {
	        //codigo de filtro
	    	modeloOrdenado = new TableRowSorter(model);
	        String fil = tfFiltro.getText().toUpperCase();
	        //filtrar todas las filas que tengan el textro "fil"
	        if (fil.length() != 0){
	                modeloOrdenado.setRowFilter (RowFilter.regexFilter(".*"+fil+"*."));
	        }else{
	                modeloOrdenado.setRowFilter (RowFilter.regexFilter(""));                
	        }
	        table.setRowSorter (modeloOrdenado);        
	    }

	
}
